package edu.jxufe.nb112.blog.admin.web.support;

import edu.jxufe.nb112.common.code.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by lvxi on 2017/11/19.
 * Note:集中处理系统异常
 */
public class SystemExceptionHandlerSupport implements HandlerExceptionResolver {
    private final static Logger LOG = LoggerFactory.getLogger(SystemExceptionHandlerSupport.class.getName());

    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception exception) {

        ModelAndView modelAndView = new ModelAndView("error/exception");
        LOG.error("系统错误",exception);
         if (exception instanceof BaseException) {
            BaseException baseException = (BaseException) exception;
            String code = baseException.getCode();
            Object[] args = baseException.getValues();
            RequestContext requestContext = new RequestContext(httpServletRequest);
            String errorMessage = requestContext.getMessage(code, args, exception.getMessage());
            modelAndView.addObject("errorMessage",errorMessage);
        }

        return modelAndView;
    }
}
